package tjs.styudy.mini.springboot.transaction.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.ObjectProvider;
import tjs.styudy.mini.springboot.transaction.config.ConnectionHolder;

import javax.sql.DataSource;
import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Nicky.Tang on 2021/10/27 9:32 下午
 *
 * @since 02.12.10
 */
public class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(ObjectProvider<DataSource> dataSourceProvider) {
        this.dataSource = dataSourceProvider.getIfAvailable();
    }

    public List<JSONObject> query(String sql) {
        // 标识MiniTransactional注解，从threadLocal中获取当前连接
        Connection connection = ConnectionHolder.getCurConnectionStatic();
        if (connection != null) {
            try (Statement stmt = connection.createStatement();
                 ResultSet rs = stmt.executeQuery(sql)) {
                return toJson(rs);
            } catch (SQLException throwables) {
                throw new RuntimeException(throwables);
            }
        }

        // 没有标识MiniTransactional注解，从连接池中获取当前连接
        try (Connection connectionNew = this.dataSource.getConnection();
             Statement stmtNew = connectionNew.createStatement();
             ResultSet rsNew = stmtNew.executeQuery(sql)) {
            return toJson(rsNew);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        }
    }

    public void execute(String sql) {
        // 标识MiniTransactional注解，从threadLocal中获取当前连接
        Connection connection = ConnectionHolder.getCurConnectionStatic();
        if (connection != null) {
            try (Statement stmt = connection.createStatement()) {
                stmt.execute(sql);
                return;
            } catch (SQLException throwables) {
                throw new RuntimeException(throwables);
            }
        }

        // 没有标识MiniTransactional注解，从连接池中获取当前连接
        try (Connection connectionNew = this.dataSource.getConnection();
             Statement stmtNew = connectionNew.createStatement()) {
            stmtNew.execute(sql);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        }
    }

    private static List<JSONObject> toJson(ResultSet rs) throws SQLException {
        List<JSONObject> res = new ArrayList<>();
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (rs.next()) {
            JSONObject jsonObj = new JSONObject();
            for (int i = 0; i < columnCount; i++) {
                String value = null;
                String columnName = metaData.getColumnLabel(i + 1);//列名称
                if (rs.getString(columnName) != null && !rs.getString(columnName).equals("")) {
                    try {
                        value = new String(rs.getBytes(columnName), "UTF-8");//列的值,有数据则转码
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    value = "";//列的值，为空，直接取出去
                }
                jsonObj.put(columnName, value);
            }
            res.add(jsonObj);
        }
        // 打印结果
        //System.out.println(JSON.toJSONString(res, false));
        return res;
    }
}
